from fastapi import APIRouter, UploadFile, File, Form
from app.services import image_service
from app.models.response import ApiResponse
from app.utils.file_utils import validate_file_type
from app.config import settings
from typing import Optional
from fastapi.responses import Response, JSONResponse
from app.services.image_service import ImageService
import logging

router = APIRouter()
logger = logging.getLogger(__name__)

@router.post(
    "/resize-photo",
    response_class=Response,
    summary="调整证件照尺寸",
    description="调整证件照片尺寸，支持多种规格"
)
async def resize_photo(
    file: UploadFile = File(...),
    photo_type: str = Form(..., description="证件照类型"),
    bg_color: str = Form("white", description="背景颜色"),
    format: str = Form("jpg", description="输出格式")
):
    """调整证件照尺寸"""
    try:
        if not photo_type:
            return JSONResponse(
                status_code=400,
                content={"message": "证件照类型不能为空"}
            )
            
        if not validate_file_type(file.filename, settings.ALLOWED_EXTENSIONS["image"]):
            return JSONResponse(
                status_code=400,
                content={"message": "不支持的文件格式"}
            )
            
        content = await file.read()
        result = await ImageService.resize_photo(content, photo_type, bg_color, format)
        
        return Response(
            content=result,
            media_type=f"image/{format}"
        )
    except ValueError as e:
        logger.error(f"调整照片尺寸失败: {str(e)}")
        return JSONResponse(
            status_code=400,
            content={"message": str(e)}
        )
    except Exception as e:
        logger.error(f"处理失败: {str(e)}")
        return JSONResponse(
            status_code=500,
            content={"message": "处理失败"}
        )

@router.post(
    "/resize",
    response_class=Response,
    summary="调整图片尺寸",
    description="按指定宽高调整图片尺寸"
)
async def resize_image(
    file: UploadFile = File(...),
    width: int = Form(...),
    height: int = Form(...)
):
    try:
        if not validate_file_type(file.filename, settings.ALLOWED_EXTENSIONS["image"]):
            return JSONResponse(
                status_code=400,
                content={"code": 400, "message": "不支持的图片格式", "data": None}
            )
        
        content = await file.read()
        result = await ImageService.resize_image(content, width, height)
        
        return Response(
            content=result,
            media_type=file.content_type
        )
    except Exception as e:
        return JSONResponse(
            status_code=400,
            content={"code": 400, "message": str(e), "data": None}
        )

@router.post(
    "/convert",
    response_class=Response,
    summary="转换图片格式",
    description="转换图片格式，支持PNG/JPG/WEBP等格式互转"
)
async def convert_image(
    file: UploadFile = File(...),
    format: str = "jpg"  # 目标格式
):
    try:
        if not validate_file_type(file.filename, settings.ALLOWED_EXTENSIONS["image"]):
            return JSONResponse(
                status_code=400,
                content={"code": 400, "message": "不支持的图片格式", "data": None}
            )
        
        content = await file.read()
        result = await image_service.convert_format(content, format)
        
        return Response(
            content=result,
            media_type=f"image/{format.lower()}"
        )
    except Exception as e:
        return JSONResponse(
            status_code=400,
            content={"code": 400, "message": str(e), "data": None}
        )

@router.post(
    "/crop",
    response_class=Response,
    summary="裁剪图片",
    description="自定义裁剪图片区域"
)
async def crop_image(
    file: UploadFile = File(...),
    x: int = 0,
    y: int = 0,
    width: int = 100,
    height: int = 100,
    format: str = "jpg"
):
    try:
        if not validate_file_type(file.filename, settings.ALLOWED_EXTENSIONS["image"]):
            return JSONResponse(
                status_code=400,
                content={"code": 400, "message": "不支持的图片格式", "data": None}
            )
        
        content = await file.read()
        result = await image_service.crop_image(content, x, y, width, height, format)
        
        return Response(
            content=result,
            media_type=f"image/{format.lower()}"
        )
    except Exception as e:
        return JSONResponse(
            status_code=400,
            content={"code": 400, "message": str(e), "data": None}
        ) 